package com.ruoyi.common.utils.excelPdfWord;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.metadata.fill.FillWrapper;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xumh
 * @title: ExcelUtil
 * @projectName ruoyi
 * @description: TODO
 * @date 2024/12/2415:17
 */
public class ExcelUtil {

    /**
     * 将数据导出为Excel文件
     * @param response
     * @param item //对象数据
     * @param dataList //List数据
     * @throws Exception
     */
    public static void dataToExcel(HttpServletResponse response,Map<String, Object> item,List<Map<String, Object>> dataList) throws Exception {
        // 设置响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("数据导出", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

        //在resources/excel下面放的模板文件
        File file = ResourceUtils.getFile("classpath:excel/settlement-template.xlsx");
        // 使用 EasyExcel 填充模板数据并写入第二个 Sheet 页
        try (FileInputStream templateFileStream = new FileInputStream(file);
             ExcelWriter excelWriter = EasyExcelFactory.write(response.getOutputStream()).withTemplate(templateFileStream).build()) {
            // 创建并写入第一个 Sheet（汇总表，使用模板）
            WriteSheet oneSheet1 = EasyExcelFactory.writerSheet(0).sheetName("结算清单").build();
            //模板里的字段是 s.name、s.age
            excelWriter.fill(new FillWrapper("s", dataList), oneSheet1);
            excelWriter.fill(item, oneSheet1);

            // 创建并写入第二个 Sheet（明细表，使用模板）
            WriteSheet userSheet2 = EasyExcelFactory.writerSheet(1).sheetName("结算明细").build();
            //模板里的字段是 d.name、d.age
            excelWriter.fill(new FillWrapper("d", dataList), userSheet2);
            excelWriter.fill(item, userSheet2);

            // 完成写入
            excelWriter.finish();
        }
    }
}
